package com.rrd.hive.udf.brickhouse.udf.collect;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory;
import org.apache.hadoop.hive.serde2.objectinspector.StandardListObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.IntObjectInspector;

@Description(name = "array_flatten",
        value = "_FUNC_(array) - Returns the array with the elements flattened.")
public class ArrayFlattenUDF extends GenericUDF {

    private ListObjectInspector listInspector;
    private StandardListObjectInspector returnInspector;
    private IntObjectInspector depthIntInspector;

    @Override
    public Object evaluate(DeferredObject[] arg0) throws HiveException {
        Object inputObject = arg0[0].get();

        if (arg0.length != 1 || inputObject == null) {
            return null;
        }

        //first, check if we are already flattened
        ObjectInspector elementInspector = this.listInspector
            .getListElementObjectInspector();
        if (elementInspector.getCategory() == Category.PRIMITIVE) {
            return inputObject;
        }

        //second, get the length of the resulting flat
        int inputLength = this.listInspector.getListLength(inputObject);
        int resultLength = 0;
        ListObjectInspector subArrayInspector = (ListObjectInspector) elementInspector;
        for (int i = 0; i < inputLength; i++) {
            resultLength += subArrayInspector.getListLength(
                this.listInspector.getListElement(inputObject, i));
        }

        //now, flatten the list by one level.
        Object flattenedListObj = this.returnInspector.create(resultLength);

        int resultIndex = 0;

        for (int i = 0; i < inputLength; i++) {
            Object element = this.listInspector.getListElement(inputObject, i);
            int subArrayLength = subArrayInspector.getListLength(element);
            for (int j = 0; j < subArrayLength; j++) {
                Object subArrayElement = subArrayInspector
                    .getListElement(element, j);
                this.returnInspector.set(flattenedListObj, resultIndex,
                    subArrayElement);
                ++resultIndex;
            }
        }

        return flattenedListObj;
    }

    @Override
    public String getDisplayString(String[] args) {
        String display = "array_flatten(" + args[0];
        if (args.length == 1) {
            display.concat(")");
        } else {
            display.concat(", " + args[1].toString() + ")");
        }
        return display;
    }

    @Override
    public ObjectInspector initialize(ObjectInspector[] arg0)
            throws UDFArgumentException {

        if (arg0.length != 1 && arg0.length != 2) { // for now, array_flatten(array). Later array_flatten(array, depth)
            throw new UDFArgumentException(
                "array_flatten : expected format array_flatten(array) or array_flatten(array, depth)");
        }

        ObjectInspector list = arg0[0];

        if (list.getCategory() != Category.LIST) {
            throw new UDFArgumentException(
                "array_flatten : expecting array as input, got "
                    + list.getTypeName());
        }

        this.listInspector = (ListObjectInspector) list;

        if (arg0.length == 2) { // should I check if this is less than 0?
            ObjectInspector depth = arg0[1];
            PrimitiveObjectInspector depthInsp = (PrimitiveObjectInspector) depth;
            if (depthInsp.getPrimitiveCategory() == PrimitiveCategory.INT) {
                this.depthIntInspector = (IntObjectInspector) depth;
            } else {
                throw new UDFArgumentException(
                    "array_flatten : expecting optional second parameter as INT");
            }
        }

        if (this.listInspector.getListElementObjectInspector()
            .getCategory() == Category.PRIMITIVE) {
            this.returnInspector = ObjectInspectorFactory
                .getStandardListObjectInspector(
                    this.listInspector.getListElementObjectInspector());
        } else {
            ListObjectInspector subArrayInspector = (ListObjectInspector) this.listInspector
                .getListElementObjectInspector();
            ;
            this.returnInspector = ObjectInspectorFactory
                .getStandardListObjectInspector(
                    subArrayInspector.getListElementObjectInspector());
        }
        return this.returnInspector;
    }
}